package com.atguigu.gmall.oms.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.exception.GmallAsyncException;
import com.atguigu.gmall.oms.entity.OrderItemEntity;
import com.atguigu.gmall.oms.service.OrderItemService;
import com.atguigu.gmall.oms.vo.OrderItemVo;
import com.atguigu.gmall.oms.vo.OrderSubmitVo;
import com.atguigu.gmall.ums.entity.UserAddressEntity;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.common.bean.PageResultVo;
import com.atguigu.gmall.common.bean.PageParamVo;

import com.atguigu.gmall.oms.mapper.OrderMapper;
import com.atguigu.gmall.oms.entity.OrderEntity;
import com.atguigu.gmall.oms.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderEntity> implements OrderService {
    @Autowired
    OrderItemService orderItemService;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Override
    public PageResultVo queryPage(PageParamVo paramVo) {
        IPage<OrderEntity> page = this.page(
                paramVo.getPage(),
                new QueryWrapper<OrderEntity>()
        );

        return new PageResultVo(page);
    }
//    @Transactional
    @Override
    public String saveOrder(String userId, OrderSubmitVo orderSubmitVo) {

        List<OrderItemVo> items = orderSubmitVo.getItems();
        if(CollectionUtils.isEmpty(items)){
            return null;
        }
        //1、判断订单是否已存在：保证幂等性
        //orderToken:是从订单开始创建到最后创建成功的唯一的标志
        String orderToken = orderSubmitVo.getOrderToken();
        Long count = baseMapper.selectCount(new LambdaQueryWrapper<OrderEntity>()
                .eq(OrderEntity::getOrderSn, orderToken));
        if(count>0){
            return null;//失败返回null
        }
        //2、订单不存在 将orderSubmitVo转为订单和订单详情存到数据库中
        //保存订单
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setUserId(Long.parseLong(userId));
        orderEntity.setOrderSn(orderToken);
        orderEntity.setCreateTime(new Date());
        //远程访问ums 查询用户数据
//        orderEntity.setUsername(orderSubmitVo.getU);
        orderEntity.setTotalAmount(orderSubmitVo.getTotalPrice());
        orderEntity.setPayAmount(orderSubmitVo.getTotalPrice());
        //远程访问sms 查询优惠信息 ：如果订单创建成功 扣掉使用的优惠券，减掉积分
        orderEntity.setPayType(1);
        orderEntity.setSourceType(0);
        orderEntity.setStatus(0);//0 待支付
        orderEntity.setDeliveryCompany(orderSubmitVo.getDeliveryCompany());
        orderEntity.setIntegration(orderSubmitVo.getTotalPrice().intValue());
        orderEntity.setGrowth(orderSubmitVo.getTotalPrice().intValue());
        orderEntity.setBillType(0);
        //收货人信息
        UserAddressEntity address = orderSubmitVo.getAddress();
        orderEntity.setReceiverName(address.getName());
        orderEntity.setReceiverPhone(address.getPhone());
        orderEntity.setReceiverPostCode(address.getPostCode());
        orderEntity.setReceiverProvince(address.getProvince());
        orderEntity.setReceiverCity(address.getCity());
        orderEntity.setReceiverRegion(address.getRegion());
        orderEntity.setReceiverAddress(address.getAddress());
        orderEntity.setConfirmStatus(0);
        orderEntity.setDeleteStatus(0);

        boolean save = this.save(orderEntity);
        if(!save){
            throw new GmallAsyncException("订单创建失败");
        }
        Long orderEntityId = orderEntity.getId();
        //3、保存订单详情
        List<OrderItemEntity> orderItemEntities = items.stream().map(orderItemVo -> {
            OrderItemEntity orderItemEntity = new OrderItemEntity();
            orderItemEntity.setOrderId(orderEntityId);
            orderItemEntity.setOrderSn(orderToken);
            orderItemEntity.setSkuId(Long.parseLong(orderItemVo.getSkuId()));
            //根据skuId查询spu 和sku的数据
            orderItemEntity.setSpuName(orderItemVo.getTitle());
            orderItemEntity.setSpuPic(orderItemVo.getDefaultImage());
//            orderItemEntity.setSpuBrand(orderItemVo.get)
            orderItemEntity.setSkuPrice(orderItemVo.getPrice());
            orderItemEntity.setSkuQuantity(orderItemVo.getCount());
            orderItemEntity.setSkuAttrsVals(JSON.toJSONString(orderItemVo.getSaleAttrs()));
            //优惠信息

            return orderItemEntity;
        }).collect(Collectors.toList());
        try {
            boolean saveBatch = orderItemService.saveBatch(orderItemEntities);
            if(!saveBatch){
                //创建的订单会回滚
                throw new GmallAsyncException("订单项保存失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            //订单项保存失败:设置订单状态为无效状态
            orderEntity.setStatus(5);
            this.updateById(orderEntity);
            //创建的订单会回滚
            throw new GmallAsyncException("订单项保存失败");
        }
        //发送定时关单的消息：需要使用延迟队列处理
        rabbitTemplate.convertAndSend("order.exchange" , "order.delay.close",
                orderToken);
        return orderToken;
    }

}